<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"  xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<meta charset="utf-8">
<head th:include="centre/manage/include :: header">
</head>

<link rel="stylesheet" type="text/css" href="/css/plugins/layui/layui.css"/>
<link href="/css/jquery-select/jquery.searchableSelect.css" rel="stylesheet" type="text/css">
<style>
    .province {
        float: left;
        position: relative;
        width: 150px;
        height: 35px;
        line-height: 35px;
        border: 1px solid #fff;
    }

    .province:hover {
        border: 1px solid #f7e4a5;
        border-bottom: 1px solid #fffec6;
        background: #fffec6;
    }

    .province .cityall {
        margin-top: 10px;
    }

    .province ul {
        list-style: outside none none;
        position: absolute;
        padding: 0;
        background: #fffec6;
        border: 1px solid #f7e4a5;
        display: none;
        width: auto;
        width: 300px;
        z-index: 999999;
        left: -26px;
        top: 33px;
    }

    .province ul li {
        float: left;
        min-width: 60px;
        margin-left: 20px;
        height: 30px;
        line-height: 30px;
    }

    .province .checkbox-inline {
        padding-top: 0;
    }

    h3, h4, h5 {
        margin: 5px 0;
        font-weight: 600;
    }

    input[type=email], input[type=url], input[type=search], input[type=tel],
    input[type=color], input[type=text], input[type=password], input[type=datetime],
    input[type=datetime-local], input[type=date], input[type=month], input[type=time],
    input[type=week], input[type=number], textarea {
        border-radius: 0 !important;
        color: #858585;
        background-color: #FFF;
        border: 1px solid #D5D5D5;
        padding: 5px 4px 6px;
        font-size: 14px;
        font-family: inherit;
        -webkit-box-shadow: none !important;
        box-shadow: none !important;
        -webkit-transition-duration: .1s;
        transition-duration: .1s;
    }

    .spectable td, .spectable th {
        border: 1px solid #ccc;
        vertical-align: middle;
        text-align: center;
    }

    .spectable th {
        font-weight: bold;
    }

    .spectableinput {
        text-align: center;
    }

    .f {
        border-color: #b94a48;
        -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
        -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    }

    .table.table-bordered tr th, .table.table-bordered tr td {
        overflow: hidden;
        text-overflow: ellipsis;
    }

    select {
        padding: 3px 4px;
        height: 30px;
    }


    .form-group .goods-thumb {
        float: left;
        margin-right: 10px;
        width: 50px;
        height: 50px;
        background-position: 50%;
        background-size: cover;
    }

    .form-group .goods-control {
        width: 400px;
        margin: 10px;
    }

    .form-group .goods-actions {
        float: right;
        margin-right: 20px;
    }
    .layui-layer-page .layui-layer-content{
        overflow: hidden !important;
    }
</style>
<body class="gray-bg">
<div class="wrapper wrapper-content">
    <div class="row">
        <div class="col-sm-12">
            <!--			<form class="form-horizontal m-t" id="signupForm">-->
            <div class="form-horizontal m-t">
                <div class="form-group">
                    <ul class="nav nav-arrow-next nav-tabs" id="myTab">
                        <li class="active"><a href="#tab_basic">活动设置</a></li>
                        <li><a href="#tab_des">商品设置</a></li>
                    </ul>
                </div>
                <div class="tab-content" style="border: 0px;">
                    <div class="tab-pane active" id="tab_basic">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">活动名称:</label>
                            <div class="col-sm-6">
                                <input id="activityName" name="activityName" placeholder="必填：活动名称"
                                       class="form-control" type="text" maxlength="100"
                                       th:value="${seckill.activityName}">
                            </div>
                            <label class="col-sm-2 control-label"
                                   style="text-align: left;color:red;">*活动名称(50个汉字以内)</label>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">开始时间:</label>
                            <div class="col-sm-6">
                                <input type="text" class=" form-control"
                                       id="startTime" name="startTime" placeholder="开始时间"
                                       onclick="laydate({istime: true, format: 'YYYY-MM-DD hh:mm:ss'})"
                                       style="background-color: #fff;" readonly="readonly"
                                       th:value="${#dates.format(seckill.startTime, 'yyyy-MM-dd')}"/>
                            </div>
                            <label class="col-sm-2 control-label" style="text-align: left;color:red;">*开始时间</label>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">结束时间:</label>
                            <div class="col-sm-6">
                                <input type="text" class=" form-control"
                                       id="endTime" name="endTime" placeholder="结束时间"
                                       onclick="laydate({istime: true, format: 'YYYY-MM-DD hh:mm:ss'})"
                                       style="background-color: #fff;" readonly="readonly"
                                       th:value="${#dates.format(seckill.endTime, 'yyyy-MM-dd')}"/>
                            </div>
                            <label class="col-sm-2 control-label" style="text-align: left;color:red;">*结束时间</label>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">限购数量:</label>
                            <div class="col-sm-6">
                                <input type="number" class=" form-control"
                                       id="purchasingCount" name="purchasingCount" placeholder="限购数量" th:value="${seckill.purchasingCount}"/>
                            </div>
                            <!--							<label class="col-sm-2 control-label" style="text-align: left;color:red;">*限购数量</label>-->
                        </div>
                        <!--						<div class="form-group">-->
                        <!--							<label class="col-sm-2 control-label">适用店铺:</label>-->
                        <!--							<div class="col-sm-6">-->
                        <!--							<input id="centreId" name="centreId"  type="hidden">-->
                        <!--							<input id="centreName" name="centreName" placeholder="点击选择店铺"-->
                        <!--								   class="form-control" type="text" readonly-->
                        <!--								   onclick="chooseCentre()">-->
                        <!--							</div>-->
                        <!--							<label class="col-sm-2 control-label" style="text-align: left;color:red;">*店铺</label>-->
                        <!--						</div>-->
                        <!--						<div class="form-group">-->
                        <!--							<label class="col-sm-2 control-label">每人限购:</label>-->
                        <!--							<div class="col-sm-2">-->
                        <!--								<input id="specTitle" type="number" name="specTitle" class="form-control">-->
                        <!--							</div>-->
                        <!--							<label class="col-sm-2 control-label" style="text-align: left;color:red;">每人可以购买</label>-->
                        <!--						</div>-->
                        <!--						<div class="form-group">-->
                        <!--							<label class="col-sm-2 control-label">订单取消:</label>-->
                        <!--							<div class="col-sm-2" style="padding-top: 7px;width: 6rem;">买家</div>-->
                        <!--							<div class="col-sm-2" style="    padding: 0;">-->
                        <!--								<input id="manudate"  type="number"  name="manudate" class="form-control">-->
                        <!--							</div>-->
                        <!--							<div class="col-sm-4" style="padding-top: 7px;">分钟后未支付订单，订单取消</div>-->
                        <!--						</div>-->

                        <div class="form-group text-center">
                            <div class="col-sm-8 col-sm-offset-2">
                                <button class="btn btn-primary" onclick="nextStep()">
                                    <i class="fa fa-check"></i>下一步
                                </button>
                            </div>
                        </div>
                    </div>
                    <!-- 商品选择开始 -->
                    <div class="tab-pane" id="tab_des">
                        &nbsp;
                        <div class="form-group good-choose">
                            <div class="col-md-12">选择商品（只能添加一件商品参与秒杀活动)</div>
                            <input type="hidden" id="id" th:value="${seckill.id}">
                            <input type="hidden" id="minPrice" th:value="${seckill.minPrice}">
                            <input type="hidden" id="maxPrice" th:value="${seckill.maxPrice}">
                            <input type="hidden" id="stock" th:value="${seckill.stock}">
                            <div class="col-md-12 col-xs-6" id="addGoods">
                                <a class="click-font-color"  onclick="chooseProduct()">选择商品</a>
                            </div>
                        </div>
                        <div class="form-group">
                            <div id="goodsInfo">

                            </div>
                        </div>

                        <div class="form-group text-center">
                            <div class="col-sm-8 col-sm-offset-2">
                                <!--														<button type="submit" class="btn btn-primary"><i class="fa fa-check"></i>提交</button>-->
                                <button class="btn btn-primary" onclick="saveProduct()">
                                    <i class="fa fa-check"></i>提交
                                </button>
                                <!--														<div class="btn btn-danger" onclick="reset()">-->
                                <!--															<i class="fa fa-remove"></i> 重置-->
                                <!--														</div>-->
                            </div>
                        </div>
                    </div>
                </div>

                <div id="goodsSeckillPrice" style="display:none;">
                    <form class="form-horizontal" style="margin-top: 15px">
                        <div class="form-group">
                            <label class="col-sm-5 control-label">秒杀价格:</label>
                            <div class="col-sm-6">
                                <input id="seckillPrice" name="displayorder" placeholder="必填：秒杀价格"
                                       class="form-control" type="number" value="0" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-5 control-label">增减活动库存:</label>
                            <div class="col-sm-6">
                                <input type="number" id="seckillStotal" name="seckillStotal" value="0"
                                       class="form-control" placeholder="必填:增减活动库存"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-5 control-label">剩余活动库存:</label>
                            <div class="col-sm-6">
                                <input type="number" id="nowSeckillStotal" name="nowSeckillStotal" value="1"
                                       class="form-control" placeholder="必填:剩余活动库存" readonly/>
                            </div>
                        </div>
                    </form>
                    <!--<div>
                        <label class="col-sm-4">秒杀价格:</label>
                        <div class="col-sm-8">
                            <input id="seckillPrice" name="displayorder" placeholder="必填：秒杀价格"
                                   class="form-control" type="number" value="0">
                        </div>
                    </div>
                    <div>
                        <label class="col-sm-4">增减活动库存:</label>
                        <div class="col-sm-8">
                            <input type="number" id="seckillStotal" name="seckillStotal" value="0"
                                   placeholder="必填:秒杀库存"/>
                        </div>

                    </div>
                    <div>
                        <label class="col-sm-4">剩余活动库存:</label>
                        <div class="col-sm-8">
                            <input type="number" id="nowSeckillStotal" name="nowSeckillStotal" value="1"
                                   placeholder="必填:修改库存数量" readonly/>
                        </div>
                    </div>-->
                </div>

            </div>
            <!--			</form>-->
        </div>
    </div>
</div>

<div th:include="centre/manage/include::footer"></div>
<script type="text/javascript" src="/js/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="/js/ueditor/ueditor.all.min.js"></script>
<script type="text/javascript" src="/js/ueditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript" src="/js/ueditor/custom.js?v=2"></script>
<script type="text/javascript" src="/js/appjs/product/AreaData.js"></script>
<script type="text/javascript" src="/public/ace/js/ace-extra.js"></script>
<script type="text/javascript" src="/js/plugins/layui/layui.js"></script>
<script type="text/javascript" src="/js/plugins/layer/layer.js"></script>
<script type="text/javascript" src="/js/bootstrap.min.js"></script>
<script src="/js/jquery-select/jquery.searchableSelect.js"></script>
<script type="text/javascript" src="/js/plugins/layui/layui.js"></script>
<script th:inline="javascript">

    var seckill = [[${seckill}]];
    console.info(seckill);
    var seckillSku = [[${seckillSku}]];
    console.info(seckillSku);
    var prefix = "/marketing/manage";

    $(function () {
        // tab切换
        $('#myTab a').click(function (e) {
            e.preventDefault();
            $('#myTab li').each(function () {
                $(this).removeClass('active')
            })
            $('.tab-content .tab-pane').each(function () {
                $(this).removeClass('active')
            })
            $(this).parent().addClass('active')
            id = $(this).attr('href')
            $(id).addClass('active');
        })

        initData();

    })

    function initData() {
        var hasoption = seckillSku.length > 0 ? 1 : 0;
        var tempRow = {
            auditing: "",
            centreId: seckill.centreId,
            costprice: 0,
            deleted: "",
            goodscode: "",
            hasoption: hasoption,
            id: seckill.productId,
            marketprice: seckill.minPrice,
            productId: "",
            productdataId: "",
            productprice: seckill.minPrice,
            status: 2,
            teamId: seckill.teamId,
            thumb: seckill.thumb,
            title: seckill.productName,
            total: seckill.stock
        }

        chooseProductCallback(tempRow);
        if (seckillSku.length > 0) {
            localStorage.setItem("productSKU", JSON.stringify(seckillSku));
        }
        if (hasoption == 1) {
            $(".seckill-price").text("秒杀价: " + "￥" + seckill.minPrice + " - " + seckill.maxPrice);
        } else {
            $(".seckill-price").text("秒杀价: " + seckill.minPrice)
        }

        $(".seckill-stock").text("秒杀库存: " + seckill.stock);
        // $("#minPrice").val(seckill.minPrice);
        // $("#maxPrice").val(seckill.maxPrice);
        // $("#stock").val(seckill.stock);


    }

    function closeDow() {
        var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
        parent.layer.close(index);
    }

    layui.use('laydate', function () {
        var laydate = layui.laydate;
        laydate.render({
            elem: '#timestart', type: 'datetime'
        });

        laydate.render({
            elem: '#timeend', type: 'datetime'
        });

        laydate.render({
            elem: '#upStartTime', type: 'datetime'
        });

        laydate.render({
            elem: '#upEndTime', type: 'datetime'
        });


    })

    function nextStep() {
        $('#myTab a[href="#tab_des"]').trigger("click");
    }

    /**
     * 选择商品
     */
    function chooseProduct() {

        // iframe层
        layer.open({
            id: 'seckill_add',
            type: 2,
            title: '选择商品',
            maxmin: true,
            shadeClose: false, // 点击遮罩关闭层
            area: ['90%', '90%'],
            content: prefix + '/toChooseProduct' // iframe的url
        });
    }

    /**
     * 选择商家
     */
    function chooseCentre() {

        // iframe层
        layer.open({
            id: 'choose_centre',
            type: 2,
            title: '选择店铺',
            maxmin: true,
            shadeClose: false, // 点击遮罩关闭层
            area: ['70%', '80%'],
            content: "/centre/manage/chooseCentre" // iframe的url
        });
    }

    function checkoption() {
        var full = true;
        if ($("#hasoption").get(0).checked) {
            $(".spec_title").each(function (i) {
                if ($(this).val() == '' || $(this).val() == undefined) {
                    layer.alert("请输入规格名称!", {icon: 5});
                    full = false;
                    return false;
                }
            });
            $(".spec_item_title").each(function (i) {
                if ($(this).val() == '' || $(this).val() == undefined) {
                    layer.alert("请输入规格项名称!", {icon: 5});
                    full = false;
                    return false;
                }
            });
        }
        if (!full) {
            return false;
        }
        return full;
    }

    var row = {};

    function chooseProductCallback(row, isOpen) {

        var html = '<a class="goods-thumb" href="' + row.thumb + '" target="_blank" rel="noopener noreferrer" style="background-image: url(' + row.thumb + ');"></a>';
        html = html + '<div class="goods-control"><div class="goods-info"><div class="goods-actions"><a class="opt click-font-color" onclick="editProduct()">编辑</a>&nbsp;&nbsp;<a class="opt click-font-color" onclick="deleteProduct()">删除</a></div></div>';
        html = html + '<h3 class="goods-title">' + row.title + '</h3>';
        html = html + '<span class="seckill-price">秒杀价：未设置</span>';
        html = html + '<span class="seckill-stock">秒杀库存：未设置</span>';
        html = html + '<p class="zent-form__help-desc">点击“编辑“修改秒杀商品的秒杀价和秒杀库存</p></div>';

        this.row = row;
        console.info(row);
        $("#goodsInfo").append(html);
        $("#addGoods").hide();

        if (isOpen) {
            if (row.hasoption == 1) {
                showSeckillPriceStock(row.id);
            } else {
                showSeckillPrice();
            }
        }

    }

    function editProduct() {
        $("#seckillPrice").val($("#minPrice").val());
        // $("#seckillStotal").val(0);
        $("#nowSeckillStotal").val($("#stock").val());
        if (this.row.hasoption == 1) {
            showSeckillPriceStock(this.row.id);
        } else {
            showSeckillPrice();
        }
    }

    function chooseCentreCallback(row) {
        console.log(row);
        $("#centreId").val(row.centreId);
        $("#centreName").val(row.shortName);
    }

    function deleteProduct() {
        $("#goodsInfo").empty();
        $("#addGoods").show();

        localStorage.removeItem("productSKU");
    }

    function showSeckillPrice() {

        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            area: ['auto'],
            shadeClose: false,
            content: $("#goodsSeckillPrice"),
            btn: ['确定', '取消'],
            yes: function (index, layero) {

                $(".seckill-price").text("秒杀价: " + $("#seckillPrice").val())
                $(".seckill-stock").text("秒杀库存: " + (parseInt($("#seckillStotal").val()) + parseInt($("#stock").val())));
                // $("#minPrice").val($("#seckillPrice").val());
                // $("#maxPrice").val($("#seckillPrice").val());
                // $("#stock").val($("#seckillStotal").val());

                layer.close(index);
            }
            , cancel: function () {
                //右上角关闭回调
                return true;// 开启该代码可禁止点击该按钮关闭
            }
        });

    }

    /**
     * 选择sku 设置类型
     */
    var index = 0;

    function showSeckillPriceStock(id) {

        index = layer.open({
            type: 2,
            title: '设置秒杀价格和库存',
            closeBtn: 0,
            area: ['100%', '100%'],
            shadeClose: false,
            content: prefix + '/toProductStockSetting?productCentreId=' + id
        });

    }

    function callBack(data) {
        console.info(data);
        var minPrice = 0;
        var maxPrice = 0;
        var stock = 0;
        for (var i = 0; i < data.length; i++) {
            var miaoshaprice = data[i].miaoshaprice;
            if (i == 0) {
                minPrice = miaoshaprice
            }

            if (minPrice > miaoshaprice) {
                minPrice = miaoshaprice;
            }
            if (maxPrice < miaoshaprice) {
                maxPrice = miaoshaprice;
            }
            stock = Number(stock) + Number(data[i].stock);
        }
        $(".seckill-price").text("秒杀价: " + "￥" + minPrice + " - " + maxPrice);
        $(".seckill-stock").text("秒杀库存: " + stock);

        // $("#minPrice").val(minPrice);
        // $("#maxPrice").val(maxPrice);
        // $("#stock").val(stock);

        if (data.length > 0) {
            localStorage.setItem("productSKU", JSON.stringify(data));
        }

    }

    function callClose() {
        layer.close(index);
    }

    $.validator.setDefaults({
        submitHandler: function () {
            saveProduct();
        }
    });

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#signupForm").validate({
            rules: {
                activityName: {
                    required: true
                },
                startTime: {
                    required: true
                },
                endTime: {
                    required: true
                }
            },
            messages: {
                activityName: {
                    required: icon + "活动名称不能为空"
                },
                startTime: {
                    required: icon + "开始时间不能为空"
                },
                endTime: {
                    required: icon + "结束时间不能为空"
                }
            }
        })
    }


    function saveProduct() {
        var sku = localStorage.getItem("productSKU");

        var activityName = $("#activityName").val();
        if (!activityName) {

            layer.tips("活动名称不能为空", '#activityName', {time: 2000, tips: 2});

            $("#activityName").focus();
            return;
        }
        var startTime = $("#startTime").val();
        if (!startTime) {
            layer.tips("开始时间不能为空", '#startTime', {time: 2000, tips: 2});

            $("#startTime").focus();
            return;
        }
        var endTime = $("#endTime").val();

        if (!endTime) {
            layer.tips("结束时间不能为空", '#endTime', {time: 2000, tips: 2});
            toastr.error("结束时间不能为空");
            $("#endTime").focus();
            return;
        }

        var productId = this.row.id;
        if (!productId) {
            layer.tips("请选择商品", '#minPrice', {time: 2000, tips: 2});
            $('#myTab a[href="#tab_des"]').trigger("click");
            return;
        }
        var centreId = this.row.centreId;
        var teamId = this.row.liansuoid;

        var productName = this.row.title;
        var thumb = this.row.thumb;

        $("#minPrice").val($("#seckillPrice").val());
        $("#maxPrice").val($("#seckillPrice").val());
        $("#stock").val($("#seckillStotal").val());

        var minPrice = $("#minPrice").val();
        var maxPrice =  $("#maxPrice").val();
        if(!maxPrice){
            layer.tips("价格不能为空!",'#maxPrice',{time:2000,tips:2});
            toastr.error("价格不能为空!");
            $("#maxPrice").focus();
            return ;
        }
        var stock =$("#stock").val();
        if(!stock){
            layer.tips("库存不能为空,请退出此界面重新修改!",'#stock',{time:2000,tips:2});
            toastr.error("库存不能为空,请退出此界面重新修改!");
            $("#stock").focus();
            return ;
        }
        if(stock<0){
            layer.tips("库存不能为负,请退出此界面重新修改!",'#stock',{time:2000,tips:2});
            toastr.error("库存不能为负,请退出此界面重新修改!");
            $("#stock").focus();
            return ;
        }
        var purchasingCount = $("#purchasingCount").val();
        var data = {
            id: seckill.id,
            centreId: centreId,
            teamId: teamId,
            activityName: activityName,
            startTime: startTime,
            endTime: endTime,
            productId: productId,
            productName: productName,
            thumb: thumb,
            minPrice: minPrice,
            maxPrice: maxPrice,
            stock: stock,
            purchasingCount:purchasingCount
        }

        var skuArray = [];
        if (sku) {
            var dataSku = JSON.parse(sku);
            for (var i = 0; i < dataSku.length; i++) {
                var tempSku = dataSku[i];
                var sku = {
                    id: tempSku.id,
                    productCentreId: tempSku.productCentreId,
                    centreId: tempSku.centreId,
                    skuId: tempSku.skuId ? tempSku.skuId : tempSku.id,//新增的时候，取的和id是同一个
                    title: tempSku.title,
                    thumb: tempSku.thumb,
                    miaoshaprice: tempSku.miaoshaprice,
                    stock: tempSku.stock,
                    specs: tempSku.specs
                }
                skuArray.push(sku);
            }
        }

        data.skus = skuArray;

        $.ajax({
            url: '/marketing/manage/saveOrUpdate',
            contentType: "application/json",
            dataType: "json",
            type: 'POST',
            data: JSON.stringify(data),
            success: function (result) {
                if (result.code == 0) {

                    layer.alert("保存成功", {icon: 6});

                } else {
                    if (result.msg != "" && result.msg != null) {
                        layer.alert(result.msg, {icon: 5});
                    } else {
                        layer.alert("保存失败，请联系管理员", {icon: 5});
                    }

                }
            }
        })
    }


</script>

</body>
</html>
